package com.example.day0820_data.slice;

import com.example.day0820_data.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ToastDialog;
import ohos.utils.net.Uri;

import java.io.*;

public class MainAbilitySlice extends AbilitySlice {

    private Text logText;

    //DataAbilityHelper为开发者提供了增删改查及批处理等方法来操作数据
    private DataAbilityHelper dataAbilityHelper;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        initComponents();
        dataAbilityHelper = DataAbilityHelper.creator(this);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void initComponents() {
        logText = (Text) findComponentById(ResourceTable.Id_text_one);
        Component readBtn = findComponentById(ResourceTable.Id_btn_bend_text);
        readBtn.setClickedListener(this::readTextFile);

    }
    //读取本地文件  第一步
    private void readTextFile(Component component) {
        try {
            FileDescriptor fileDescriptor
                    = dataAbilityHelper.openFile(Uri.parse("dataability:///com.example.day0820_data.Data_Ability/document?Test_Text.txt"), "r");
            if (fileDescriptor == null) {
                new ToastDialog(this).setText("文件不存在").show();
                return;
            }
            //如果正常 显示文件
            showText(fileDescriptor);
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    //显示文件的方法 将磁盘文件读取到DevEco中 第三步
    private void showText(FileDescriptor fileDescriptor) {
        try {
            FileInputStream fileInputStream = new FileInputStream(fileDescriptor);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
            String line = "";
            StringBuffer stringBuffer = new StringBuffer();
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
                stringBuffer.append("\n");
            }
            //设置显示
            logText.setText(stringBuffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
